﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SysMisc
{
    public static class Common
    {
        /// <summary>
        /// 强制退出程序
        /// </summary>
        public static void ExitApplication()
        {
            System.Environment.Exit(0);
        }

        public static string bit2str(long size)
        {
            double d_sz = size;
            if (d_sz > 1024 * 1024 * 1024 / 2)
            {/*以GB为单位*/
                return (d_sz / (1024 * 1024 * 1024)).ToString("f2") + "G";
            }
            else if(d_sz > 1024 * 1024 / 2)
            {/*以MB为单位*/
                return (d_sz / (1024 * 1024)).ToString("f2") + "M";
            }
            else if (d_sz > 1024 / 2)
            {/*以MB为单位*/
                return (d_sz / (1024)).ToString("f2") + "K";
            }
            else
            {/*以B为单位*/
                return (d_sz).ToString("f2") + "B";
            }
        }

        public static string GetMD5OfString(string encryptString)
        {
            byte[] result = Encoding.Default.GetBytes(encryptString);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            string encryptResult = BitConverter.ToString(output).Replace("-", "");
            return encryptResult;
        }

        /// <summary>
        /// 清空指定路径下的文件和文件夹
        /// </summary>
        /// <param name="srcPath">待清空的文件夹的路径名</param>
        public static void ClearDirectory(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Error(typeof(Common), e);
            }
        }
    }
}
